package com.meishij.fragment.finddetail;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.meishij.R;
import com.meishij.adapter.FindRegionSelectorAdapter;
import com.meishij.customerview.cityindex.City;
import com.meishij.customerview.cityindex.SectionBar;
import com.meishij.entry.CityEntry;
import com.meishij.utils.PinYinUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.meishij.R.raw.city;

/**
 * Created by 阿飞 on 2016/10/14.
 */

public class FindRegionActivity extends AppCompatActivity implements View.OnClickListener {

    private ListView lvCity;
    private SectionBar sbCity;
    private String region;
    private FindRegionSelectorAdapter regionSelectorAdapter;
    private TextView selectIndex;

    private final int HANDLER_HIDE_SELEINDEX = 1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_HIDE_SELEINDEX:
                    selectIndex.setVisibility(View.GONE);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_detail_region);
        getArguments();
        initView();
        setRegion();
    }

    private void getArguments() {
        Intent getIntent = getIntent();
        if (getIntent != null) {
            region = getIntent.getStringExtra("region");
        }
    }

    private void initView() {
        View back = findViewById(R.id.iv_find_detail_header_back);
        back.setOnClickListener(this);

        TextView title = (TextView) findViewById(R.id.tv_find_detail_header_title);
        title.setText("选择城市");

        lvCity = (ListView) findViewById(R.id.lv_find_detail_region);
        sbCity = (SectionBar) findViewById(R.id.sb_find_detail_city);
        selectIndex = ((TextView) findViewById(R.id.tv_find_detail_region_selectIndex));
        sbCity.setOnSectionBarSelectedListener(new SectionBar.OnSectionBarSelectedListener() {
            @Override
            public void getSection(String selectedSection) {
                selectIndex.setVisibility(View.VISIBLE);
                selectIndex.setText(selectedSection);
                handler.removeMessages(HANDLER_HIDE_SELEINDEX);
                handler.sendEmptyMessageDelayed(HANDLER_HIDE_SELEINDEX, 1500);
            }
        });
    }

    private void setRegion() {

        final InputStream inputStream = getResources().openRawResource(city);
        final InputStreamReader isr = new InputStreamReader(inputStream);
        BufferedReader reader = new BufferedReader(isr);
        StringBuilder jsonBuilder = new StringBuilder();
        String readLine = null;
        try {
            while ((readLine = reader.readLine()) != null) {
                jsonBuilder.append(readLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String json = jsonBuilder.toString();
        if (TextUtils.isEmpty(json)) {
            Toast.makeText(this, "加载城市信息失败", Toast.LENGTH_SHORT).show();
            return;
        }
        List<CityEntry> cityInfos = null;
        Type cityType = new TypeToken<List<CityEntry>>() {
        }.getType();
        try {
            cityInfos = new Gson().fromJson(json, cityType);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (cityInfos == null || cityInfos.size() == 0) {
            Toast.makeText(this, "加载城市信息失败", Toast.LENGTH_SHORT).show();
            return;
        }

        final List<City> citys = new ArrayList<>();

        if (!TextUtils.isEmpty(region)) {
            City city = new City();
            city.setId("#");
            city.setName(region);
            citys.add(city);
        }

        for (CityEntry cityInfo : cityInfos) {
            String cityName = cityInfo.getText();
            if (cityName.endsWith("市")) {
                City city = new City();
                String cityPinYin = PinYinUtil.getPinyin(cityName);
                String cityId = cityPinYin.subSequence(0, 1).toString().toUpperCase();
                city.setId(cityId);
                city.setName(cityName);
                citys.add(city);
            } else {
                for (CityEntry.ChildrenBean cityChildren : cityInfo.getChildren()) {
                    City city = new City();
                    String cityChildrenName = cityChildren.getText();
                    String cityChildrenPinYin = PinYinUtil.getPinyin(cityChildrenName);
                    String cityChildrenId = cityChildrenPinYin.subSequence(0, 1).toString().toUpperCase();
                    city.setId(cityChildrenId);
                    city.setName(cityChildrenName);
                    citys.add(city);
                }
            }
        }
        Collections.sort(citys);

        regionSelectorAdapter = new FindRegionSelectorAdapter(this, citys);
        lvCity.setAdapter(regionSelectorAdapter);
        sbCity.setListView(lvCity);
        lvCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                City selectedCity = citys.get(position);
                Intent resultIntent = new Intent();
                resultIntent.putExtra("region", selectedCity.getName());
                setResult(100, resultIntent);
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_find_detail_header_back:
                finish();
                break;
        }
    }
}
